<template>
  <div class="order-page">
    <div class="loading-container">
      <div class="loading-animation">
        <div class="seat-icon">
          <i class="el-icon-user"></i>
        </div>
        <div class="pulse-rings">
          <div class="ring"></div>
          <div class="ring"></div>
          <div class="ring"></div>
        </div>
      </div>
      <h2 class="loading-text">正在为您抢占座位</h2>
      <p class="loading-tip">请稍候，系统正在处理您的预约请求...</p>
      
      <div class="booking-info" v-if="bookingData">
        <div class="info-item">
          <span class="label">自习室</span>
          <span class="value">{{ bookingData.roomName }}</span>
        </div>
        <div class="info-item">
          <span class="label">座位号</span>
          <span class="value">{{ bookingData.seatInfo.seatNumber }}</span>
        </div>
        <div class="info-item">
          <span class="label">位置</span>
          <span class="value">{{ bookingData.seatInfo.position }}</span>
        </div>
        <div class="info-item">
          <span class="label">日期</span>
          <span class="value">{{ bookingData.date }}</span>
        </div>
        <div class="info-item">
          <span class="label">时段</span>
          <span class="value time">{{ formatTimeSlots(bookingData.timeSlots) }}</span>
        </div>
        <div class="info-item total">
          <span class="label">费用</span>
          <span class="value price">￥{{ bookingData.price }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'OrderPage',
  data() {
    return {
      bookingData: null,
      loading: true
    }
  },
  created() {
    // 检查登录状态
    const token = localStorage.getItem('token')
    if (!token) {
      this.$message.warning('请先登录')
      // 保存当前页面路径，登录后返回
      localStorage.setItem('redirect', this.$route.fullPath)
      this.$router.push('/login')
      return
    }

    // 从localStorage获取预约数据
    const bookingDataStr = localStorage.getItem('bookingData')
    if (bookingDataStr) {
      this.bookingData = JSON.parse(bookingDataStr)
      this.submitBooking()
    } else {
      this.$message.error('预约数据获取失败')
      this.$router.push('/study-room')
    }
  },
  methods: {
    formatTimeSlots(slots) {
      if (!slots || !slots.length) return ''
      return slots
        .sort((a, b) => new Date(a.originalTime) - new Date(b.originalTime))
        .map(slot => slot.time)
        .join(', ')
    },
    async submitBooking() {
      try {
        // 再次检查token
        const token = localStorage.getItem('token')
        if (!token) {
          this.$message.warning('登录已过期，请重新登录')
          localStorage.setItem('redirect', this.$route.fullPath)
          this.$router.push('/login')
          return
        }

        // 获取第一个时间段的开始时间和最后一个时间段的结束时间
        const sortedTimeSlots = this.bookingData.timeSlots.sort((a, b) => 
          new Date(a.originalTime) - new Date(b.originalTime)
        );
        
        // 从时间字符串中提取小时数
        const getTimeFromString = (timeStr) => {
          const [start, end] = timeStr.split('-');
          return {
            startHour: parseInt(start.split(':')[0]),
            endHour: parseInt(end.split(':')[0])
          };
        };

        // 使用time字符串中的开始和结束时间
        const { startHour, endHour } = getTimeFromString(sortedTimeSlots[0].time);
        
        console.log('预约时间:', {
          date: this.bookingData.date,
          startTime: `${startHour.toString().padStart(2, '0')}:00:00`,
          endTime: `${endHour.toString().padStart(2, '0')}:00:00`
        });
        
        const res = await request({
          url: '/api/admin/order/takeOrder',
          method: 'post',
          headers: {
            'Authorization': token
          },
          data: {
            roomId: Number(this.bookingData.roomId),
            seatId: Number(this.bookingData.seatId),
            bookingDate: this.bookingData.date,
            startTime: `${startHour.toString().padStart(2, '0')}:00:00`,
            endTime: `${endHour.toString().padStart(2, '0')}:00:00`
          }
        })

        // 延迟2秒模拟抢座过程
        await new Promise(resolve => setTimeout(resolve, 2000))

        if (res.code === 200) {
          // 预约成功，等待动画播放完毕后跳转
          this.$message.success(res.message || '预约成功')
          localStorage.removeItem('bookingData')
          this.$router.push('/admin/study-room/myOrder')
        } else {
          this.$message.error(res.message || '预约失败')
          setTimeout(() => {
            this.$router.push('/admin/study-room/myOrder')
          }, 1500)
        }
      } catch (error) {
        if (error.response && error.response.status === 403) {
          this.$message.warning('请先登录')
          localStorage.setItem('redirect', this.$route.fullPath)
          this.$router.push('/login')
        } else {
          console.error('预约失败:', error)
          this.$message.error('预约失败，请重试')
          setTimeout(() => {
            this.$router.push('/room/detail/' + this.bookingData.roomId)
          }, 1500)
        }
      }
    }
  }
}
</script>

<style scoped>
.order-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #1a73e8, #34a853);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.loading-container {
  background: white;
  border-radius: 16px;
  padding: 40px;
  text-align: center;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
  max-width: 500px;
  width: 90%;
}

.loading-animation {
  position: relative;
  width: 120px;
  height: 120px;
  margin: 0 auto 30px;
}

.seat-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 60px;
  height: 60px;
  background: #409EFF;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2;
}

.seat-icon i {
  font-size: 30px;
  color: white;
}

.pulse-rings {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.ring {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100%;
  height: 100%;
  border-radius: 50%;
  border: 2px solid #409EFF;
  animation: pulse 2s infinite;
}

.ring:nth-child(2) {
  animation-delay: 0.5s;
}

.ring:nth-child(3) {
  animation-delay: 1s;
}

@keyframes pulse {
  0% {
    transform: translate(-50%, -50%) scale(0.5);
    opacity: 1;
  }
  100% {
    transform: translate(-50%, -50%) scale(1.5);
    opacity: 0;
  }
}

.loading-text {
  font-size: 24px;
  color: #303133;
  margin: 0 0 10px;
}

.loading-tip {
  color: #909399;
  margin: 0 0 30px;
}

.booking-info {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
  text-align: left;
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  font-size: 15px;
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-item .label {
  color: #909399;
}

.info-item .value {
  color: #303133;
  font-weight: 500;
}

.info-item .value.time {
  color: #409EFF;
}

.info-item.total {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px dashed #dcdfe6;
}

.info-item.total .value.price {
  color: #F56C6C;
  font-size: 24px;
  font-weight: bold;
}

@media (max-width: 768px) {
  .loading-container {
    padding: 30px 20px;
  }
  
  .loading-animation {
    width: 100px;
    height: 100px;
    margin-bottom: 20px;
  }
  
  .seat-icon {
    width: 50px;
    height: 50px;
  }
  
  .seat-icon i {
    font-size: 24px;
  }
  
  .loading-text {
    font-size: 20px;
  }
  
  .info-item {
    font-size: 14px;
  }
  
  .info-item.total .value.price {
    font-size: 20px;
  }
}
</style> 